﻿using ExcelSystem.Model;
using ExcelSystem.ToolHelper;
using ExcelSystem.ViewModelsClass;
using ImTools;
using Newtonsoft.Json;
using NPOI.Util;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ExcelSystem.ViewModels
{
    public class BOMAddViewModel : BindableBase, IDialogAware
    {
        public string Title =>"";

        ExcelContext db;

        private BOMViewModel bom;
        public BOMViewModel Bom
        {
            get { return bom; }
            set { SetProperty(ref bom, value); }
        }

        private List<NSMaterialsViewModel> nsMaterials;
        public List<NSMaterialsViewModel> NSMaterials
        {
            get { return nsMaterials; }
            set { SetProperty(ref nsMaterials, value); }
        }
        private MaterialViewModel model;


        public event Action<IDialogResult> RequestClose;

        private DelegateCommand<string> changeParCommand;
        /// <summary>
        /// 修改参数
        /// </summary>
        public DelegateCommand<string> ChangeParCommand
        {
            get { return changeParCommand; }
            set { SetProperty(ref changeParCommand, value); }
        }


        private DelegateCommand<string> saveCommand;
        /// <summary>
        ///  保存
        /// </summary>
        public DelegateCommand<string> SaveCommand
        {
            get { return saveCommand; }
            set { SetProperty(ref saveCommand, value); }
        }

        private DelegateCommand<string> deleteCommand;
        /// <summary>
        ///  保存
        /// </summary>
        public DelegateCommand<string> DeleteCommand
        {
            get { return deleteCommand; }
            set { SetProperty(ref deleteCommand, value); }
        }



        private DelegateCommand<string> weightFormulaCommand;
        /// <summary>
        ///    重量
        /// </summary>
        public DelegateCommand<string> WeightFormulaCommand
        {
            get { return weightFormulaCommand; }
            set { SetProperty(ref weightFormulaCommand, value); }
        }

        private DelegateCommand<string> dataFixCommand;
        /// <summary>
        ///   数据补全
        /// </summary>
        public DelegateCommand<string> DataFixCommand
        {
            get { return dataFixCommand; }
            set { SetProperty(ref dataFixCommand, value); }
        }







        private readonly IRegionManager regionManage;
        private readonly IDialogService dialogService;
        BOMAddViewModel(IRegionManager regionManage, IDialogService dialogService)
        {
            //数据库文档
            db = ExcelContentFactory.GetInstance() ;
            //依赖注入
            this.regionManage = regionManage;
            this.dialogService = dialogService;
            ChangeParCommand = new DelegateCommand<string>(ChangePar);
            SaveCommand = new DelegateCommand<string>(Save);
            DeleteCommand = new DelegateCommand<string>(Delete);
            WeightFormulaCommand = new DelegateCommand<string>(WeightFormula);
            DataFixCommand= new DelegateCommand<string>(DataFix);
            Init();
        }

      

        private void Save(string obj)
        {
            // 补全信息
            var ns = NSMaterials.FirstOrDefault(t => t.NSMaterial.ID == Bom.Data.ChannelSteelID);
            if (ns != null)
            {
                Bom.Data.ChannelSteel = ns.AllName;
            }
            if (db.BOMs.Count(t=>t.MaterialNo== Bom.Data.MaterialNo)!=0)
            {
                db.BOMs.Update(Bom.Data);
            }
            else
            {
                db.BOMs.Add(Bom.Data);
            }
         
            db.SaveChanges();
            MessageBox.Show("保存成功");

        }

        private void Delete(string obj)
        {
           
            db.BOMs.Remove(Bom.Data);
            db.SaveChanges();
            MessageBox.Show("删除成功");
        }

        private void Init()
        {
            Bom =new BOMViewModel() {  Data=new BOM()};
            Bom.RibbedFormula = "板筋重";
            NSMaterials =new List<NSMaterialsViewModel>();
            db.NSMaterials.ToList().ForEach(t => {

                NSMaterials.Add(new NSMaterialsViewModel()
                {
                    NSMaterial = t,
                    AllName = t.Name + t.Type,
                });
            });
          
        }

        private void ChangePar(string obj)
        {
            DialogParameters keyValuePairs = new DialogParameters();
            keyValuePairs.Add("id", obj);
            dialogService.Show("BOMInfo", keyValuePairs, null);
        }

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
           
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            if (parameters != null && parameters.ContainsKey("id"))
            {

                var id = parameters.GetValue<string>("id");
                if(!string.IsNullOrEmpty(id) )
                {
                    Bom.Data = db.BOMs.FirstOrDefault(t => t.ID == int.Parse(id));
                    var ns= db.NSMaterials.FirstOrDefault(t => Bom.Data.ChannelSteel.Contains(t.Name.Contains("H") ? "H" : t.Name)
                    && Bom.Data.ChannelSteel.Contains(t.Type)
                    );
                    if(ns!=null)
                    Bom.Data.ChannelSteelID= ns.ID;


                }

               
              
            }
            if (parameters != null && parameters.ContainsKey("data"))
            {

                model = parameters.GetValue<MaterialViewModel>("data");
                if (model != null)
                {
                    var fbdata = db.BOMs.FirstOrDefault(t => t.MaterialNo == model.Material.MaterialNo);
                    if(fbdata!=null)
                    {
                        Bom.Data= fbdata;
                    }
                    else
                    {
                        string id = model.Material.MaterialNo.Split('-')[1];
                        var data = db.BOMs.FirstOrDefault(t => t.MaterialNo == id);
                        Bom.Data = SetProperty(data);
                        Bom.Data.MaterialNo = model.Material.MaterialNo;
                    }
                   
                }



            }
        }

        private BOM SetProperty(BOM oldValue)
        {
            BOM newValue =new BOM();

            newValue.GetType().GetProperties().ForEach(t =>
            {
                oldValue.GetType().GetProperties().ForEach(p =>
                {
                    if (p.Name == t.Name&&p.Name!="ID")
                    {
                        var name = p.GetValue(oldValue);
                        t.SetValue(newValue, name);
                    }
                       

                });

            });


            return newValue;
        }

        /// <summary>
        /// 重量计算公式
        /// </summary>
        public void WeightFormula(string par)
        {
            //板筋
            if (par == "RibbedPlate")
            {
                try
                {
                    if(!string.IsNullOrEmpty(Bom.Data.RibbedPlateType)&& Bom.Data.RibbedPlateNumber!=null)
                    {
                        var list = Bom.Data.RibbedPlateType.Split("*");
                        if(list!=null&&list.Count()==3)
                        {
                            Bom.Data.RibbedPlateWeight = Convert.ToDecimal(list[0]) * Convert.ToDecimal(list[1]) * Convert.ToDecimal(list[2]) / 1000 / 1000 * 7.85m;
                            Bom.RibbedFormula = $"{Bom.Data.RibbedPlateType} /1000000*7.85={Bom.Data.RibbedPlateWeight}";
                            if (Bom.Data.RibbedPlateWeight!=null&& Bom.Data.RopeHeadWeight!=null)
                            {
                                Bom.Data.Counterweight = Bom.Data.RibbedPlateWeight * Bom.Data.RibbedPlateNumber + Bom.Data.RopeHeadWeight * Bom.Data.RopeHeadNumber;
                            }
                           

                            RaisePropertyChanged(nameof(Bom));

                        }
                    }
                }
                catch { }
               
            }
            //板筋
           else if (par == "RopeHead")
            {
                try
                {
                    if (!string.IsNullOrEmpty(Bom.Data.RopeHeadType) && Bom.Data.RopeHeadNumber != null)
                    {
                        var list = Bom.Data.RopeHeadType.Split("*");
                        if (list != null && list.Count() == 3)
                        {
                            Bom.Data.RopeHeadWeight = Convert.ToDecimal(list[0]) * Convert.ToDecimal(list[1]) * Convert.ToDecimal(list[2])  / 1000 / 1000 * 7.85m;
                            Bom.RopeHeadFormula = $"{Bom.Data.RopeHeadType} /1000000*7.85={Bom.Data.RopeHeadWeight}";
                            if (Bom.Data.RibbedPlateWeight != null && Bom.Data.RopeHeadWeight != null)
                            {
                                Bom.Data.Counterweight = Bom.Data.RibbedPlateWeight * Bom.Data.RibbedPlateNumber + Bom.Data.RopeHeadWeight * Bom.Data.RopeHeadNumber;
                            }
                            RaisePropertyChanged(nameof(Bom));

                        }
                    }
                }
                catch { }

            }
        }


        /// <summary>
        /// 数据补全
        /// </summary>
        /// <param name="par"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void DataFix(string par)
        {
            //钢丝绳孔
            if (par == "WireRopeHole")
            {
                if (!string.IsNullOrEmpty(Bom.Data.WireRopeHole))
                {
                    Bom.Data.WireRopeHole= Bom.Data.WireRopeHole.Replace("孔", "");
                    Bom.Data.WireRopeHole=Bom.Data.WireRopeHole+ "孔";
                    RaisePropertyChanged(nameof(Bom));

                }
            }
        }
    }
}
